﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

namespace YXShop.Web.membercenter.shop.shop_administer
{
    public partial class shop_add : System.Web.UI.Page
    {
        YXShop.BLL.Shop.Shop shopBll = new YXShop.BLL.Shop.Shop();
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                InitWebControl();
                GetModel();
            }
        }


        #region 验证
        private void InitWebControl()
        {
            YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
            this.txtArea.Attributes.Add("readonly", "readonly");
            this.txtArea.Attributes.Add("onclick", "selectFile('Area',new Array(" + this.txtAreaValue.ClientID + "," + this.txtArea.ClientID + "),310,450,'" + sp.DummyPaht + "');");
            this.txtStyle.Attributes.Add("readonly", "readonly");
            this.txtStyle.Attributes.Add("onclick", "selectFile('ShopStyle',new Array(" + this.hfstyle.ClientID + "," + this.txtStyle.ClientID + "),310,450,'" + sp.DummyPaht + "');");
            ChangeHope.WebPage.WebControl.Validate(this.txtName, "店铺名称不能为空", "isnull", "必填", "该项为必填项");
            ChangeHope.WebPage.WebControl.Validate(this.txtTwoDomain, "店铺二级域名不能为空", "isnull", "必填", "该项为必填项");
            ChangeHope.WebPage.WebControl.Validate(this.txtStyle, "店铺风格不能为空", "isnull", "必填", "该项为必填项");
            ChangeHope.WebPage.WebControl.Validate(this.txtAffiche, "店铺公告不能为空", "isnull", "必填", "该项为必填项");
            ChangeHope.WebPage.WebControl.Validate(this.txtArea, "该店铺属于哪个分站的,不填写则不属于任何分站，只属于该主站内容(分站关闭无法填写)", "no", "", "");
            this.Form.Attributes.Add("onsubmit", "return CheckForm()");
            BindType();
            if (!sp.IsCloseStation)
            {
                this.txtArea.Enabled = false;
            }
            BindRadionList(rblStyle, -1, -1);
            BindDropDownList(ddlWork, -1);
        }
        #endregion

        #region 类型
        private void BindType()
        {
            YXShop.BLL.Shop.ShopCategory cateBll = new YXShop.BLL.Shop.ShopCategory();
            List<YXShop.Model.Shop.ShopCategory> cateList = cateBll.GetAll();
            this.ddlType.DataSource = cateList;
            this.ddlType.DataTextField = "Name";
            this.ddlType.DataValueField = "ID";
            this.ddlType.DataBind();
        }
        #endregion

        #region 店铺等级
        private void BindRadionList(RadioButtonList rbtnList, int shopRank, int minDay)
        {
            ////用户不能修改为比已使用天数更少的规模方案
            rbtnList.Items.Clear();
            YXShop.BLL.Shop.ShopLevel levelBll = new YXShop.BLL.Shop.ShopLevel();
            List<YXShop.Model.Shop.ShopLevel> levelList = levelBll.GetAll();
            ListItem item = null;
            foreach (YXShop.Model.Shop.ShopLevel level in levelList)
            {
                item = new ListItem();
                item.Value = string.Format("{0},{1}", level.ID, level.ExpendDays.ToString());
                item.Text = string.Format("<font style='color:red;'>{0}</font> 租金：{1}元<br />&nbsp;&nbsp; 经营数量{2}个,空间{3}kb,使用[{4}]天", level.Name, level.Price.ToString(), level.ProCount.ToString(), level.ShopSpace.ToString(), level.ExpendDays.ToString());
                if (shopRank == level.ID)
                {
                    item.Selected = true;
                }
                if (minDay == 1)
                {
                    item.Enabled = false;
                }
                rbtnList.Items.Add(item);
                item = null;
            }
        }
        #endregion

        #region 绑定主营
        private void BindDropDownList(DropDownList ddl, int TypeID)
        {
            List<YXShop.Model.Product.Productclass> shoplist = ItemsSort();
            ListItem item = null;

            foreach (YXShop.Model.Product.Productclass category in shoplist)
            {
                string pre = "";
                for (int i = 1; i < category.Parentpath.Split(',').Length; i++)
                {
                    pre += "|-";
                }
                item = new ListItem();
                item.Value = category.ID.ToString();
                item.Text = pre + category.Name;
                if (TypeID == category.ID)
                {
                    item.Selected = true;
                }
                ddl.Items.Add(item);
                item = null;
            }
        }
        private List<YXShop.Model.Product.Productclass> ItemsSort()
        {
            YXShop.BLL.Product.Productclass classBll = new YXShop.BLL.Product.Productclass();
            List<YXShop.Model.Product.Productclass> classList = classBll.GetAll();
            List<YXShop.Model.Product.Productclass> newclasslist = new List<YXShop.Model.Product.Productclass>(classList.Count + 5);
            foreach (YXShop.Model.Product.Productclass item in classList)
            {
                if (item.Fatherid == 0)
                {
                    newclasslist.Add(item);
                    GetChildItems(ref newclasslist, ref classList, item.ID);
                }
            }
            return newclasslist;
        }
        private void GetChildItems(ref List<YXShop.Model.Product.Productclass> newcateList, ref List<YXShop.Model.Product.Productclass> oldcateList, int parID)
        {
            foreach (YXShop.Model.Product.Productclass item in oldcateList)
            {
                if (Convert.ToInt32(item.Fatherid) == parID)
                {
                    newcateList.Add(item);
                    GetChildItems(ref newcateList, ref oldcateList, item.ID);
                }
            }
        }
        #endregion

        protected void btnChange_Click(object sender, EventArgs e)
        {
            Save();
        }

        #region 保存修改
        private void Save()
        {
            YXShop.Model.Shop.Shop shop = new YXShop.Model.Shop.Shop();
            if (Session["MemberID"] != null)
            {
                shop.Uid = Convert.ToInt32(Session["MemberID"]);
            }
            else
            {
                this.ltlMsg.Text = "操作失败,用户失效请重新登陆";
                this.pnlMsg.Visible = true;
                this.pnlMsg.CssClass = "actionErr";
                return;
            }

            int shopRank = 0, addDay = 0;
            string[] arr = this.rblStyle.SelectedValue.Split(',');
            if (arr.Length == 2)
            {
                shopRank = ChangeHope.Common.ValidateHelper.IsNumber(arr[0]) ? Convert.ToInt32(arr[0]) : 0;
                addDay = ChangeHope.Common.ValidateHelper.IsNumber(arr[1]) ? Convert.ToInt32(arr[1]) : 0;
            }
            if (FileUploadSign.HasFile)
            {
                ChangeHope.Common.UploadFile uf = new ChangeHope.Common.UploadFile();
                uf.ExtensionLim = ".gif,.jpg,.jpeg,.dmp";
                uf.FileLengthLim = 4000;
                uf.PostedFile = this.FileUploadSign;
                uf.SavePath = "/yxuploadfile/shop/sign";
                if (uf.Upload())
                {
                    if (uf.HaveLoad)
                    {
                        shop.Shopsign = uf.FilePath;
                    }
                }
                else
                {
                    this.ltlMsg.Text = "操作失败，" + uf.Message + "";
                    this.pnlMsg.Visible = true;
                    this.pnlMsg.CssClass = "actionErr";
                    return;
                }
            }
            else
            {
                if (ViewState["sign"] != null)
                {
                    shop.Shopsign = ViewState["sign"].ToString();
                }
                else
                {
                    this.ltlMsg.Text = "操作失败,请上传店标";
                    this.pnlMsg.Visible = true;
                    this.pnlMsg.CssClass = "actionErr";
                    return;
                }
            }
            if (FileUploadPic.HasFile)
            {
                ChangeHope.Common.UploadFile ufw = new ChangeHope.Common.UploadFile();
                ufw.ExtensionLim = ".gif,.jpg,.jpeg,.dmp";
                ufw.FileLengthLim = 4000;
                ufw.PostedFile = this.FileUploadPic;
                ufw.SavePath = "yxuploadfile/shop/authentication";
                if (ufw.Upload())
                {
                    if (ufw.HaveLoad)
                    {
                        shop.Attestationpic = ufw.FilePath;
                    }
                }
                else
                {
                    this.ltlMsg.Text = "操作失败，" + ufw.Message + "";
                    this.pnlMsg.Visible = true;
                    this.pnlMsg.CssClass = "actionErr";
                    return;
                }
            }
            else
            {
                if (ViewState["pic"] != null)
                {
                    shop.Attestationpic = ViewState["pic"].ToString();
                }
                else
                {
                    this.ltlMsg.Text = "操作失败,请上传认证图片";
                    this.pnlMsg.Visible = true;
                    this.pnlMsg.CssClass = "actionErr";
                    return;
                }
            }
           

            shop.Shopname = this.txtName.Text.Trim().ToString();
            shop.Shoptype = Convert.ToInt32(this.ddlType.SelectedValue);
            shop.Categories = Convert.ToInt32(this.ddlWork.SelectedValue);
            shop.Shoprank = Convert.ToInt32(shopRank);//等级
            shop.Affiche = this.txtAffiche.Text.Trim().ToString();
            shop.Startdate = Convert.ToDateTime(System.DateTime.Now.ToShortDateString());
            shop.Enddate = Convert.ToDateTime(shop.Startdate).AddDays(addDay);
            shop.State = 0;
            shop.Shopstyle = Convert.ToInt32(this.hfstyle.Value);
            shop.Twodomainname = this.txtTwoDomain.Text.Trim().ToString();
            shop.Attestationstate = 0;
            shop.Prestigerank = 0;
            shop.Visitno = 0;
            shop.Attribute = "0,0,0,0,0,0";
            shop.Addtime = Convert.ToDateTime(System.DateTime.Now);
            shop.Updatetime = Convert.ToDateTime(System.DateTime.Now);
            shop.Shopstate = 0;
            shop.Shopnum = GetUniqueID(Convert.ToInt32(Session["MemberID"]));
            shop.Areatid = this.txtAreaValue.Value != string.Empty ? this.txtAreaValue.Value : "0";//地址
            shop.Content = this.txtStoreContent.Value;
           
            string type = ChangeHope.WebPage.PageRequest.GetQueryString("type");
            if (type != null && type.Equals("edit"))
            {
                List<YXShop.Model.Shop.Shop> shopList = shopBll.GetListShopByWhere(" uid=" + Session["MemberID"].ToString());
                if (shopList != null && shopList.Count == 1)
                {
                    shop.Sid = Convert.ToInt32(shopList[0].Sid);
                    shop.Discription = shopList[0].Discription;
                }
                int count = shopBll.Update(shop);
                if (count > 0)
                {
                    ChangeHope.WebPage.BasePage.PageRight("店铺信息修改成功。", "shop_add.aspx");
                }
                else
                {
                    ChangeHope.WebPage.BasePage.PageError("店铺申请失败。", "shop_add.aspx");
                }
                
            }
            else
            {
                shop.Discription = "暂无";
                int count = shopBll.Add(shop);
                if (count > 0)
                {
                    ChangeHope.WebPage.BasePage.PageRight("店铺申请成功。", "../shop_product/product_info_edit.aspx");
                }
                else
                {
                    ChangeHope.WebPage.BasePage.PageError("店铺申请失败。", "shop_add.aspx");
                }
            }
        }
        #endregion

        #region  编号
        private string GetUniqueID(int uid)
        {
            int len = uid.ToString().Length;
            string pre = "";
            for (int i = 0; i < 6 - len; i++)
            {
                pre += "0";
            }
            return pre + uid.ToString();
        }
        #endregion

        #region 初始
        private void GetModel()
        {  
            if (Session["MemberID"]!=null)
            {
                List<YXShop.Model.Shop.Shop> shoplist = shopBll.GetListShopByWhere(" uid=" + Session["MemberID"].ToString());
                if (shoplist != null && shoplist.Count == 1)
                {
                    YXShop.Model.Shop.Shop shop = shoplist[0];
                    this.txtName.Text = shop.Shopname;
                    this.ddlType.SelectedValue = shop.Shoptype.ToString();
                    this.ddlWork.SelectedValue = shop.Categories.ToString();
                    this.txtTwoDomain.Text = shop.Twodomainname;
                    YXShop.BLL.Shop.ShopLevel levelBll = new YXShop.BLL.Shop.ShopLevel();
                    YXShop.Model.Shop.ShopLevel level = levelBll.GetModelByID(Convert.ToInt32(shop.Shoprank));
                    string styleValue = string.Empty;
                    if(level!=null)
                    {
                        styleValue = shop.Shoprank.ToString() + "," + level.ExpendDays.ToString();
                    }
                    this.rblStyle.SelectedValue = styleValue;
                    this.txtStyle.Text = GetNameType(Convert.ToInt32(shop.Shopstyle));
                    this.txtAffiche.Text = shop.Affiche.ToString();
                    this.txtArea.Text = AreaName(shop.Areatid);
                    this.txtAreaValue.Value = shop.Areatid;
                    this.txtStoreContent.Value = shop.Content;
                    ViewState["pic"] = shop.Attestationpic;
                    ViewState["sign"] = shop.Shopsign;
                }
              
            }
        }
        #endregion

        #region 绑定样式
        private string GetNameType(int typeId)
        {
            YXShop.BLL.Shop.ShopColor colorBll = new YXShop.BLL.Shop.ShopColor();
            YXShop.Model.Shop.ShopColor color = colorBll.GetModel(typeId);
            if (color != null)
            {
                this.hfstyle.Value = color.Id.ToString();
                return color.Name.ToString();
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 绑定区域
        protected string AreaName(string id)
        {
            string[] AreaIdStr = id.Split(',');
            string reStr = "";
            YXShop.BLL.SystemInfo.Provinces bll = new YXShop.BLL.SystemInfo.Provinces();
            for (int i = 0; i < AreaIdStr.Length; i++)
            {
                YXShop.Model.SystemInfo.Provinces model = bll.GetModel(Convert.ToInt32(AreaIdStr[i]));
                if (model != null)
                {
                    if (reStr == "")
                    {
                        reStr = model.CityName;
                    }
                    else
                    {
                        reStr = reStr + "," + model.CityName;
                    }
                }
            }
            return reStr;
        }
        #endregion
    }
}
